<?php include dirname(__FILE__).'/common/header.php'; ?>

<?php include dirname(__FILE__).'/common/menu.php'; ?>

var attr = {};
	attr.project_type_list = [['1','网页'],['2','手机']];

	list.grid = new ZM.GridPanel({
		url: list.baseUrl + 'project/getProjectList',
		history:'project_id',
		onlyShow: true,
		region: 'center',
		tbar:[{
			text:'新建项目',
			cls:'btn-show',
			hidden:!Ext.permission['project/createProject'.toLowerCase()],
			iconCls:'icon-create',
			handler:function() {
				var frm = new ZM.FormPanel({
					url:list.baseUrl + 'project/createProject',
					keySubmit:false,
					success:function(res) {
						ZM.bo.msg('success',res.detail);
						list.grid.store.reload();
						win.close();
					},
					items:[{
						fieldLabel:'项目名称',
						name:'project_name',
						allowBlank:false
					},{
						fieldLabel:'项目编码',
						name:'project_code',
						allowBlank:false
					},{
						fieldLabel:'项目状态',
						name:'project_status',
						value:1,
						xtype:'hidden'
					},{
						fieldLabel:'项目类型',
						allowBlank:false,
						name:'project_type',
						xtype: 'radiogroupfield',
						columns:[60,60],
						options:attr.project_type_list
			        },{
						fieldLabel:'手机屏幕宽',
						name:'project_device_width'
					}]
				});
				var win = new ZM.PopUp({
					title:'新建项目',
					items:frm,
					type:'s'
				});
				win.show();
			}
		}],
		columns:[
			//{header: "ID" , dataIndex: 'project_id',hidden:true},
			{header: "项目名称", dataIndex: 'project_name',filter:{},width:200},
			{header: "项目编码", dataIndex: 'project_code',filter:{},width:200},
			{header: "样式版本", dataIndex: 'project_version',width:80},
			{header: "手机屏幕宽", dataIndex: 'project_device_width',width:80},
			/*
			{header: "项目类型", dataIndex: 'project_type',width:80,renderer:function(val){
				return ZM.id2name(val,attr.project_type_list);
			}},
			*/
			{header: "项目状态", dataIndex: 'project_status',width:65,renderer:ZM.status,filter:{
				xtype:"combofield",
				listWidth:180,
				value:1,
				options:[['','全部'],['1','开启'],['0','关闭']]
			}},
	
			//{header: "创建时间", dataIndex: 'project_time_create',width:140},
			{header: "操作", dataIndex: '', renderer:function(v,p,r){
				var str = "";
				str += Ext.rd('编辑','fireEdit',r,'project/editProject');
				str += Ext.rd('编辑CSS','fireEditCSS',r,'project/getProjectCss');
				str += Ext.rd('编辑JS','fireEditJS',r,'project/getProjectJs');
				//str += Ext.rd('images','fireViewFileList',r,'project/getProjectFileList');
				str += '<a href="'+list.baseUrl+'project/dp/'+r.json.id+'" target="_blank">[頁面下载]</a>';
				//if(r.json.sprite_exists) {
				//	str += Ext.rd('sprite.png preview','fireViewSprite',r,'project/getSprite');
				//}
				str += Ext.rd('代码段','fireCode',r,'project/getCodeList');
				str += Ext.rd('文件','fireImportFile',r,'project/getCommonFileList');
				//str += Ext.rd('下载资源包','fireDownloadResource',r,'project/downloadProjectPackage');
				//str += Ext.rd('pages','fireDownloadPages',r,'project/downloadStaticPackage');
				if(r.json.project_status==1){
					str += Ext.rd('隐藏','fireDisable',r,'project/disableProject');
				}else{
					str += Ext.rd('显示','fireActive',r,'project/activeProject');
				}
				return str;
			}}
		]
	});

	list.grid.fireEdit = function(r) {
		var r = r.json;
		var frm = new ZM.FormPanel({
			url:list.baseUrl + 'project/editProject',
			keySubmit:true,
			params:{project_id:r.project_id},
			success:function(res) {
				ZM.bo.msg('success',res.detail);
				list.grid.store.reload();
				win.close();
			},
			items:[{
				fieldLabel:'项目名称',
				name:'project_name',
				value:r.project_name,
				allowBlank:false
			},{
				xtype:'radiogroupfield',
				fieldLabel:'项目类型',
				name:'project_type',
				options:attr.project_type_list,
				columns:[60,60],
				value:r.project_type,
				allowBlank:false
			},
			{
				fieldLabel:'样式版本号',
				maxLength:10,
				value:r.project_version,
				name:'project_version'
			},{
				fieldLabel:'手机屏幕宽',
				name:'project_device_width',
				value: r.project_device_width,
				xtype:'intfield'
			}]
		});
		var win = new ZM.PopUp({
			title:'编辑项目',
			items:frm,
			type:'s'
		});
		win.show();
	}

	list.grid.fireActive = function(r) {
		var r = r.json;
		
		ZM.ajax({
			url: list.baseUrl + 'project/activeProject',
			params:{project_id:r.project_id},
			success:function(res){
				ZM.bo.msg('success!',res.detail);
				list.grid.store.reload();
			}
		});
		
	}

	list.grid.fireDisable = function(r) {
		var r = r.json;
		ZM.ajax({
			url: list.baseUrl + 'project/disableProject',
			params:{project_id:r.project_id},
			success:function(res){
				ZM.bo.msg('success!',res.detail);
				list.grid.store.reload();
			}
		});
			
	}
	
	list.grid.fireEditCSS = function(r) {
		var r = r.json;
		var content = '';
		var toClose = false;
		var frm = new ZM.FormPanel({
			url:list.baseUrl+'project/editProjectCss',
			params:{project_id:r.project_id},
			keySubmit:false,
			focusField: false,
			success:function(res) {
				ZM.bo.msg('成功!',res.detail);
				content = Ext.getCmp('field_project_css_content').getValue();
				frm.getForm().findField('project_css_id').setValue(res.addon.project_css_id);
			},
			tbar:[{
				text:'保存',
				cls:'btn-show',
				iconCls:'icon-save',
				hidden:!Ext.permission['project/editProjectCss'.toLowerCase()],
				handler:function(){
					ZM.submitForm(frm);
				}
			}],
			items:[
				{
					xtype:'hidden',
					name:'project_css_id'
				},
				{
					xtype:'textarea',
					hideLabel:true,
					name:'project_css_content',
					id:'field_project_css_content',
					plugins:[new ZM.tabKey()],
					width: 900,
					height:400
				}
			],
			buttons:null
		});
		var win = new ZM.PopUp({
			title:'编辑项目['+r.project_name+']的CSS',
			type:'l',
			layout:'fit',
			items:frm,
			listeners:{
				beforeclose:function(w) {
					if(toClose) return true; 
					if(Ext.getCmp('field_project_css_content').getValue() != content) {
						Ext.Msg.confirm('确认?','未保存改变的内容，您确定要关闭吗?',function(btn) {
							if(btn == 'yes') {
								win.close();
								toClose = true;
							}
						});
						return false;
					}
				}
			}
		});
		win.show();
		frm.getEl().mask('数据获取中...','x-mask-loading');
		ZM.ajax({
			url: list.baseUrl + 'project/getProjectCss',
			params:{project_id:r.project_id},
			success:function(res) {
				frm.getForm().findField('project_css_content').setValue(res.addon.project_css_content);
				frm.getForm().findField('project_css_id').setValue(res.addon.project_css_id);
				frm.getEl().unmask();
				content = res.addon.project_css_content;
				//Ext.get('field_project_css_content').update(content);
				//CodeMirror.fromTextArea(document.getElementById("field_project_css_content"), {lineNumbers: true});
			},
			failure:function(res) {
				Ext.Msg.alert('失败','获取数据失败!点击确定关闭窗口!',function(){
					win.close();
				});
			}
		});
	}

	list.grid.fireEditJS = function(r) {
		var r = r.json;
		var content = '';
		var toClose = false;
		var frm = new ZM.FormPanel({
			url:list.baseUrl+'project/editProjectJS',
			params:{project_id:r.project_id},
			keySubmit:false,
			focusField: false,
			success:function(res) {
				ZM.bo.msg('成功!',res.detail);
				content = Ext.getCmp('field_project_js_content').getValue();
				frm.getForm().findField('project_js_id').setValue(res.addon.project_js_id);
			},
			tbar:[{
				text:'保存',
				cls:'btn-show',
				iconCls:'icon-save',
				hidden:!Ext.permission['project/editProjectJS'.toLowerCase()],
				handler:function(){
					ZM.submitForm(frm);
				}
			}],
			items:[
				{
					xtype:'hidden',
					name:'project_js_id'
				},
				{
					xtype:'textarea',
					hideLabel:true,
					name:'project_js_content',
					id:'field_project_js_content',
					plugins:[new ZM.tabKey()],
					width: 900,
					height:400
				}
			],
			buttons:null
		});
		var win = new ZM.PopUp({
			title:'编辑项目['+r.project_name+']的JS',
			type:'l',
			items:frm,
			layout:'fit',
			listeners:{
				beforeclose:function(w) {
					if(toClose) return true;
					if(Ext.getCmp('field_project_js_content').getValue() != content) {
						Ext.Msg.confirm('确认?','未保存改变的内容，您确定要关闭吗?',function(btn) {
							if(btn == 'yes') {
								toClose = true;
								win.close();
							}
						});
						return false;
					}
				}
			}
		});
		win.show();
		frm.getEl().mask('数据获取中...','x-mask-loading');
		ZM.ajax({
			url: list.baseUrl + 'project/getProjectJs',
			params:{project_id:r.project_id},
			success:function(res) {
				frm.getForm().findField('project_js_content').setValue(res.addon.project_js_content);
				frm.getForm().findField('project_js_id').setValue(res.addon.project_js_id);
				frm.getEl().unmask();
				content = res.addon.project_js_content;
				//Ext.get('field_project_js_content').update(content);
				//CodeMirror.fromTextArea(document.getElementById("field_project_js_content"), {lineNumbers: true,matchBrackets: true});
			}
		});
	}
	
	list.grid.fireDetail = list.grid.fireViewFileList = function(r) {
		if(!Ext.permission['project/getProjectFileList'.toLowerCase()]) return;
		var r = r.json;
		
		list.project_id = r.project_id;
		list.detail.show().ownerCt.doLayout();
		fileGrid.store.baseParams = {project_code:r.project_code};
		fileGrid.store.load();

	}
	
	list.grid.fireViewSprite = function(r) {
		var r = r.json;
		var win = new ZM.PopUp({
			type: 'l',
			title: '项目['+r.project_name+']拼图预览[/uploads/'+r.project_code+'/sprite.png]',
			layout: 'border',
			items:[{
				xtype:'container',
				region: 'west',
				id: 'view_image',
				autoScroll: true,
				width: 700
			},{
				xtype: 'gridpanel',
				region: 'center',
				id: 'grid_sprite_css',
				onlyShow: true,
				bbar: null,
				columns: [
					{header: 'ID',dataIndex:'sprite_id',hidden: true},
					{header: 'sprite 对应的 CSS',dataIndex:'sprite_css',renderer:function(val) {
						val = val.replace(/-0px/g,0);
						return '<code><pre>'+val+'</pre></code>';
					}}
				]
			}],
			listeners: {
				close:function() {
					Ext.get('sprite_mask').hide();
				}
			}
		});
		win.show();
		win.getEl().mask('数据读取中...','x-mask-loading');
		var grid = Ext.getCmp('grid_sprite_css');
		grid.on('rowclick',function(g,index) {
			var r = g.store.getAt(index);
			var imgXY = Ext.getCmp('view_image').getEl().child('img').getXY();
			var cntPos = Ext.getCmp('view_image').getPosition();
			var left = imgXY[0]-2+parseInt(r.get('sprite_x'));
			var top = imgXY[1]-2+parseInt(r.get('sprite_y'));
			var w = r.get('sprite_width');
			var h = r.get('sprite_height');
			if(left < cntPos[0]) left = cntPos[0];
			if(top < cntPos[1]) top = cntPos[1];
			if(left + w > cntPos[0]+Ext.getCmp('view_image').getWidth()) w = cntPos[0]+Ext.getCmp('view_image').getWidth() - left;
			if(top + h > cntPos[1]+Ext.getCmp('view_image').getHeight()) h = cntPos[1]+Ext.getCmp('view_image').getHeight() - top;
			Ext.get('sprite_mask').show().applyStyles({
				left: left+'px',
				top: top+'px',
				width: w+'px',
				height: h+'px'
			});
		});
		if(!Ext.get('sprite_mask')) {
			Ext.DomHelper.append(Ext.getBody(),{
				tag:'div',
				id: 'sprite_mask',
				style: 'position:absolute;background-color:blue;opacity:0.3;border:2px solid red;z-index:100000000;'
			});
			Ext.get('sprite_mask').setVisibilityMode(Ext.Element.DISPLAY).hide();
		}
		ZM.ajax({
			url: list.baseUrl + 'project/getSprite',
			params: {project_id:r.project_id},
			success: function(res) {
				var el = Ext.getCmp('view_image').getEl();
				el.update('<img src="'+res.addon.sprite_url+'?'+new Date().valueOf()+'">');
				el.child('img').on('click',function(e,t) {
					var imgXY = this.getXY();
					var posX = e.xy[0] - imgXY[0];
					var posY = e.xy[1] - imgXY[1];
					Ext.get('sprite_mask').hide();
					grid.store.each(function(r) {
						if(posX > r.get('sprite_x')-0 && posX < r.get('sprite_x')-0 + r.get('sprite_width')
							&& posY > r.get('sprite_y')-0 && posY < r.get('sprite_y')-0 + r.get('sprite_height')) {
							grid.getSelectionModel().selectRecords([r]);
							var rowIndex = grid.store.indexOf(r);
							//console.log(rowIndex);
							grid.getView().getRow(rowIndex).scrollIntoView();
							return false;
						}
					});
				});
				win.getEl().unmask();
				grid.store.removeAll();
				Ext.each(res.items,function(v,i){
					grid.store.add(new Ext.data.Record(v));
				});
			},
			failure: function(res) {
				win.getEl().unmask();
			}
		});
	}
	
	list.grid.fireImportFile = function(r) {
		var r = r.json;
		var fileGrid = new ZM.GridPanel({
			url: list.baseUrl + 'project/getCommonFileList',
			params:{project_id:r.project_id},
			onlyShow: true,
			bbar:null,
			tbar:[{
				text:'保存',
				iconCls:'icon-save',
				hidden:!Ext.permission['project/editCommonFileList'.toLowerCase()],
				cls:'btn-show',
				handler:function(){
					var datas = fileGrid.getSelectionModel().selections;
					var params = {project_id:r.project_id};
					if(datas.items.length> 0) {
						Ext.each(datas.items,function(val,i) {
							params['common_file['+i+']'] = val.json.file_name;
						});
					} else {
						params['common_file[]'] = '';
					}
					fileGrid.getEl().mask('数据保存中...','x-mask-loading');
					ZM.ajax({
						url: list.baseUrl + 'project/editCommonFileList',
						params: params,
						success:function(res){
							ZM.bo.msg('成功!',res.detail);
							fileGrid.getEl().unmask();
							win.close();
						},
						failure:function(res) {
							fileGrid.getEl().unmask();
							Ext.Msg.alert('失败!',res.detail);
						}
					});
				}
			}],
			columns:[
				sm,
				{header:'文件名',dataIndex:'file_name',width:260},
				{header:'状态',dataIndex:'file_status',renderer:ZM.status}
			],
			listeners : {
				'afterrender' : function(grid){
					grid.store.on('load', function(store, records, options){
						var rows = [];
						Ext.each(records,function(r,i){
							if(r.get('file_status')){
								rows.push(store.indexOf(r));//row index
							};
						});
						grid.getSelectionModel().selectRows(rows,true);
					}); 
				}
			}
		});
		var win = new ZM.PopUp({
			title:'项目['+r.project_name+']引入文件',
			items:fileGrid
		});
		win.show();
		fileGrid.store.load();
	}

	list.grid.fireCode = function(r) {
		var r = r.json;
		var codeGrid = new ZM.GridPanel({
			url: list.baseUrl + 'project/getCodeList',
			params:{project_id:r.project_id},
			onlyShow: true,
			bbar:null,
			tbar:[{
				text:'保存',
				iconCls:'icon-save',
				hidden:!Ext.permission['project/getCodeList'.toLowerCase()],
				cls:'btn-show',
				handler:function(){
					var datas = codeGrid.getSelectionModel().selections;
					var params = {project_id:r.project_id};
					if(datas.items.length> 0) {
						Ext.each(datas.items,function(val,i) {
							params['project_code_ids['+i+']'] = val.json.code_id;
						});
					}
					codeGrid.getEl().mask('数据保存中...','x-mask-loading');
					ZM.ajax({
						url: list.baseUrl + 'project/editLinkedCode',
						params: params,
						mask:codeGrid,
						success:function(res){
							ZM.bo.msg('成功!',res.detail);
							win.close();
						},
						failure:function(res) {
							Ext.Msg.alert('失败!',res.detail);
						}
					});
				}
			}],
			columns:[
				sm,
				{header:'代码名称',dataIndex:'code_name',width:320},
				{header:'状态',dataIndex:'code_linked',renderer:ZM.status}
			],
			listeners : {
				'afterrender' : function(grid){
					grid.store.on('load', function(store, records, options){
						var rows = [];
						Ext.each(records,function(r,i){
							if(r.get('code_linked')){
								rows.push(store.indexOf(r));//row index
							};
						});
						grid.getSelectionModel().selectRows(rows,true);
					}); 
				}
			}
		});
		var win = new ZM.PopUp({
			title:'项目['+r.project_name+']引入代码',
			items:codeGrid
		});
		win.show();
		codeGrid.store.load();
	}
	
	list.grid.fireDownloadResource = function(r) {
		var r = r.json;
		Ext.Msg.confirm('确认?','确定要导出['+r.project_name+']?',function(btn) {
			if(btn == 'yes') {
				location.href = list.baseUrl + 'project/downloadProjectPackage/'+r.project_id;
			}
		});
	}

	list.grid.fireDownloadPages = function(r) {
		var r = r.json;
		Ext.Msg.confirm('确认?','确定要导出['+r.project_name+']?',function(btn) {
			if(btn == 'yes') {
				location.href = list.baseUrl + 'project/downloadStaticPackage/'+r.project_id;
			}
		});
	}
	
	var fileGrid = new ZM.GridPanel({
		url: list.baseUrl + 'project/getProjectFileList',
		history: 'project_file_id',
		onlyShow: true,
		bbar:null,
        autoExpandColumn : 'path',
		columns:[
			{header:'文件名',dataIndex:'project_file_name',width:150},
			{header:'缩略图',dataIndex:'project_file_url',renderer:ZM.cellImage},
			{header:'文件路径',dataIndex:'project_file_html',id:'path'},
			{header:'更新时间',dataIndex:'project_file_time_lastmodified'},
			{header:'文件大小(kB)',dataIndex:'project_file_size',width:80,renderer:function(val){
                if(val > 180){
                    return '<span style="color:red;">' + val + '</span>';
                }else{
                    return val;
                }
            }},
			
			{header: "操作", dataIndex: '',width:190,renderer:function(v,p,r){
					var str = "";
					str += '<a id="_'+r.id+'" title="fireDetail" href="#">[查看图片]</a>';
					str += '<a href="/download.php?file='+r.json.project_file_url+'" target="_blank">[下载]</a>';
					
					if(r.json.project_file_name != 'sprite.png')
						str += Ext.rd('删除','fireRemoveFile',r,'project/removeProjectFile');
					
					return str;
				}
			}
		]
	});

	fileGrid.fireRemoveFile = function(r) {
		var r = r.json;
		Ext.Msg.confirm('确认?','确定要删除文件['+r.project_file_name+']?',function(btn){
			if(btn == 'yes') {
				fileGrid.getEl().mask('正在删除中...','x-mask-loading');
				ZM.ajax({
					url: list.baseUrl + 'project/removeProjectFile',
					params:{project_file_path:r.project_file_path},
					success:function(res) {
						ZM.bo.msg('成功!',res.detail);
						fileGrid.getEl().unmask();
						fileGrid.store.reload();
					},
					failure:function(res) {
						fileGrid.getEl().unmask();
					}
				});
			}
		});
	}
	

	
	fileGrid.fireDetail = function(r) {
		viewImageInWindow(this,r,{name:'project_file_name',url:'project_file_url'});
	}
	

	
	list.detail = new ZM.detailPanel({
		tbar:[{
				xtype:'fileuploadfield',
				multiple:'multiple',
				name:'project_file[]',
				buttonText:'上传文件',
				buttonOnly:true,
				hideLabel:true,
				allowBlank:false,
				listeners:{
					'fileselected':function(f,v) {
						var el = f.fileInput.dom,url = list.baseUrl+'project/addImage/'+list.project_id;

			

			    		if(el.files.length==0){
			      			return;
			    		}

			    		var xhrs = [], xhrimages = [];

			    		for(var index=0; index<el.files.length; index++){
					      var File = el.files[index];

					      xhrs[index] = new XMLHttpRequest();
					      xhrs[index].index = index;
					      xhrs[index].open('post', url, true);
					      xhrs[index].setRequestHeader("Content-Type", "application/octet-stream");
					      xhrs[index].setRequestHeader("X-FILENAME", encodeURI(File.name)||'file');
					      xhrs[index].setRequestHeader("X-File-Size", File.fileSize);
					      xhrs[index].setRequestHeader("X-File-Type", File.type);
			      
					      xhrs[index].onreadystatechange = function(){
					        if (this.readyState == 4 && this.status == 200){
					          var r = {};
					          try {
					            r = eval("(" + this.responseText + ")");
					          } catch(err){}
					          if(r.success){
					            xhrimages[this.index]=r.addon.sprite_url;
					          
					            if(xhrs.length==xhrimages.length){
					                fileGrid.store.reload();
					            }
					          }else{
					            alert(r.detail);
					          }
					        }
					      };

					      if ('getAsBinary' in File){
					        xhrs[index].sendAsBinary(File.getAsBinary());
					      }else{
					        xhrs[index].send(File);
					      }
					    }//eof of for
					 }//enf of selected
				 }//end of listener

		  }],
		items:fileGrid
	});
	
	function viewImageInWindow(grid,r,fields){
		var curIndex = 0,
			name = fields.name,
			url = fields.url;
		var store = grid.getStore();
		for(var i = 0 ; i < store.getCount();i++) {
			if(store.getAt(i).id == r.id) {
				curIndex = i;
				break;
			}
		}
		var r = r.json;
		var win = new ZM.PopUp({
			title:'查看图片['+r[name]+']',
			tbar:[{
				text:'上一张',
				cls:'btn-show',
				id:'tb-prev',
				disabled: curIndex ==0,
				handler:function() {
					curIndex -= 1;
					var r = store.getAt(curIndex).json;
					Ext.getCmp('image-cpt').el.update(isImage(r[url])?'<img src="'+r[url]+'">':'非图片');
					win.setTitle('查看图片['+r[name]+']');
					if(curIndex == 0 ) {
						this.disable();
					}
					Ext.getCmp('tb-next').enable();
				}
			},'-',{
				text:'下一张',
				cls:'btn-show',
				id:'tb-next',
				disabled: curIndex ==store.getCount()-1,
				handler:function() {
					curIndex += 1;
					var r = store.getAt(curIndex).json;
					Ext.getCmp('image-cpt').el.update(isImage(r[url])?'<img src="'+r[url]+'">':'非图片');
					win.setTitle('查看图片['+r[name]+']');
					if(curIndex == store.getCount()-1 ) {
						this.disable();
					}
					Ext.getCmp('tb-prev').enable();
				}
			}],
			items:[
				{xtype:'container',
				id:'image-cpt',
				html:isImage(r[url])?'<img src="'+r[url]+'">':'非图片'
				}
			]
		}).show();
		function isImage(url) {
			var suffixes = ['.jpg','.png','.gif'];
			var name = url.substring(url.length-4,url.length);
			for(var i = 0 ; i < suffixes.length;i++) {
				if(suffixes[i] == name) return true;
			}
			return false;
		}
	}

<?php include dirname(__FILE__).'/common/layout.php'; ?>
	list.grid.store.baseParams = {'project_status':1};
	list.grid.store.load();
<?php include dirname(__FILE__).'/common/footer.php'; ?>
